package com.bookstore.servlet;

import com.bookstore.entity.User;
import com.bookstore.service.UserService;
import com.bookstore.service.impl.UserServiceImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

@WebServlet("/client/user.do")
public class UserServlet extends BaseServlet {
    UserService userService = new UserServiceImpl();

    protected void queryAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<User> users = userService.queryAllUsers();
        //拿到响应的字符输出流
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write(new Gson().toJson(users));
    }

    protected void register(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String email = req.getParameter("email");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String telephone = req.getParameter("telephone");
        String gender = req.getParameter("gender");
        String introduction = req.getParameter("introduction");
        User user = new User(null, username, password, gender, email, telephone, introduction, null, 0, 0, new Date());
        int result = userService.register(user);
        //拿到响应的字符输出流
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if (result >= 1) {
            writer.write("1");
        } else {
            writer.write("0");
        }
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = userService.login(new User(username, password));
        //拿到响应的字符输出流
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if (user != null) {
            writer.write("1");
            req.getSession().setAttribute("user", user);
        } else {
            writer.write("0");
        }
    }

    protected void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.销毁session
        request.getSession().invalidate();
        //2.重定向回首页
        response.sendRedirect(request.getContextPath() + "/client/login.html");
    }
}
